package com.pinyoumei.app.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.ProductDetailActivity;
import com.pinyoumei.app.activity.ProductDetailPtActivity;
import com.pinyoumei.app.adapter.SecondListAdapter;
import com.pinyoumei.app.adapter.SecondTopAdapter;
import com.pinyoumei.app.bean.GoodDetailsBean;
import com.pinyoumei.app.bean.SecondBean;
import com.pinyoumei.app.bean.SectionBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.view.CircularImageView;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.MarqueeView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@SuppressLint("ValidFragment")
public class SecondFragment extends BaseLazyLoadFragment {
    private String mTitle;
    private MarqueeView marquee_view1;
    private MarqueeView marqueeView2;
    private LinearLayout parentView;
    private SecondListAdapter secondListAdapter;
    private SecondTopAdapter secondTopAdapter;
    private int page = 1;
    private LoadingDailog loadingDailog;
    private Gson gson;
    private ImageView iv_top_banner_img;
    private RecyclerView recyclerView;
    private String sId = "";
    private List<SectionBean.SectionDto> sectionDtos = null;


    public static SecondFragment getInstance(String title) {
        SecondFragment sf = new SecondFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_second;
    }

    @Override
    public void initView(View view) {
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        gson = new Gson();

        iv_top_banner_img = view.findViewById(R.id.iv_top_banner_img);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.HORIZONTAL, false));
        secondTopAdapter = new SecondTopAdapter(getContext(),R.layout.top_item_view, null);
        recyclerView.setAdapter(secondTopAdapter);
        secondTopAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                page = 1;
                sId = sectionDtos.get(position).getId();
                for (int i=0;i<sectionDtos.size();i++){
                    sectionDtos.get(i).setSelect(false);
                }
                sectionDtos.get(position).setSelect(true);
                secondTopAdapter.notifyDataSetChanged();
                InitData();
            }
        });

        marquee_view1 = view.findViewById(R.id.marquee_view1);
        marqueeView2 = view.findViewById(R.id.marquee_view2);
//        parentView = view.findViewById(R.id.marqueeLayout);

        RecyclerView rv_1 = view.findViewById(R.id.rv_1);
        rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        secondListAdapter = new SecondListAdapter(R.layout.item_second, null);
        rv_1.setAdapter(secondListAdapter);

        secondListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (secondListAdapter.getData() != null && secondListAdapter.getData().size() > 0) {

                    InitGoodDate(secondListAdapter.getData().get(position).getId());

                }


            }


        });

        SmartRefreshLayout smartRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);

        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                LoadMoreData();
                refreshLayout.finishLoadMore();
            }


            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                RefreshData();
                refreshLayout.finishRefresh();
            }
        });
    }

    @Override
    public void onFragmentFirst() {
        super.onFragmentFirst();

        sectionList();
    }

    private void sectionList() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        OkGo.<String>post(Constants.sectionList)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        SectionBean bean = gson.fromJson(response.body(), SectionBean.class);
                        if (bean.getCode() >= 0) {
                            sectionDtos = bean.getResult().getSection_list();
                            for (int i=0;i<bean.getResult().getSection_list().size();i++){
                                sectionDtos.get(i).setSelect(i==0?true:false);
                            }
                            secondTopAdapter.setNewData(sectionDtos);
                        } else {
                            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                        InitData();
                    }

                });
    }


    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", page);
        map.put("limit", 6);
        map.put("section_id", sId);
        OkGo.<String>post(Constants.GOODS_LIST)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", page)
                .params("limit", 6)
                .params("section_id", sId)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        SecondBean secondBean = gson.fromJson(response.body(), SecondBean.class);

                        if (secondBean.getCode() >= 0) {
                            secondListAdapter.setNewData(secondBean.getResult().getGoods_list());
                            Glide.with(getActivity()).load(secondBean.getResult().getTop_banner_img()).into(iv_top_banner_img);

                            List<SecondBean.ResultBean.NoteListBean> note_list = secondBean.getResult().getNote_list();
                            if (note_list != null && note_list.size() > 0) {
                                for (int i = 0; i < note_list.size(); i++) {

                                    View tabView = View.inflate(getActivity(), R.layout.item_loop_second, null);
                                    CircularImageView iv_user_head_img = tabView.findViewById(R.id.iv_user_head_img);
                                    TextView tv_note_content = tabView.findViewById(R.id.tv_note_content);

                                    Glide.with(getActivity()).load(note_list.get(i).getUser_head_img()).into(iv_user_head_img);
                                    tv_note_content.setText(note_list.get(i).getNote_content());
                                    if (i<=3){
                                        marquee_view1.addViewInQueue(tabView);
                                        marquee_view1.setScrollSpeed(5);
                                        marquee_view1.setScrollDirection(MarqueeView.RIGHT_TO_LEFT);
                                        marquee_view1.setViewMargin(155);//间距
                                        marquee_view1.startScroll();
                                    }else{
                                        marqueeView2.addViewInQueue(tabView);
                                        marqueeView2.setScrollSpeed(5);
                                        marqueeView2.setScrollDirection(MarqueeView.RIGHT_TO_LEFT);
                                        marqueeView2.setViewMargin(160);//间距
                                        marqueeView2.startScroll();
                                    }

                                }

                            }


                        } else {
                            Toast.makeText(getActivity(), secondBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }

    private void RefreshData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", page);
        map.put("limit", 6);
        map.put("section_id", sId);
        OkGo.<String>post(Constants.GOODS_LIST)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", page)
                .params("limit", 6)
                .params("section_id", sId)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        SecondBean secondBean = gson.fromJson(response.body(), SecondBean.class);

                        if (secondBean.getCode() >= 0) {
                            secondListAdapter.setNewData(secondBean.getResult().getGoods_list());
                            Glide.with(getActivity()).load(secondBean.getResult().getTop_banner_img()).into(iv_top_banner_img);
                        } else {
                            Toast.makeText(getActivity(), secondBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void LoadMoreData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("page", page);
        map.put("limit", 6);
        map.put("section_id", sId);
        OkGo.<String>post(Constants.GOODS_LIST)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("page", page)
                .params("limit", 6)
                .params("section_id", sId)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        SecondBean secondBean = gson.fromJson(response.body(), SecondBean.class);

                        if (secondBean.getCode() >= 0) {
                            secondListAdapter.addData(secondBean.getResult().getGoods_list());
                        } else {
                            Toast.makeText(getActivity(), secondBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }


    private void InitGoodDate(String goods_id) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(getActivity()));
        map.put("goods_id", goods_id);


        OkGo.<String>post(Constants.GOODS_LIST_DETAIL)
                .params("user_id", SPUtils.getAppUserId(getActivity()))
                .params("goods_id", goods_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        GoodDetailsBean goodDetailsBean = gson.fromJson(response.body(), GoodDetailsBean.class);
                        Utils.isActivity = "2";
                        if (goodDetailsBean.getCode() >= 0) {
                            if (goodDetailsBean.getResult().getData_info().getIs_can_pt() == 1) {
                                Intent intent = new Intent(getActivity(), ProductDetailPtActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
                                intent.putExtra("goodDetailsBean", goodDetailsBean);
                                intent.putExtra("goods_id", goods_id);
                                startActivity(intent);
                            }

                        } else {
                            Toast.makeText(getActivity(), goodDetailsBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }
}